﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace System.Windows.KExtensions
{   
    /// <summary>
    /// Represents a character range with starting value and length
    /// </summary>
    internal class PositionedWord {

        private static char[] WORD_BREAK = { '\n', '\r', ' ', '.', ',', ';', ':', '"', '\'', '!', '?', '(', ')', '[',']', '\\','/', '+', '-', '<','>','%','#','@','&','*','{','}' };

        /// <summary>
        /// First character in range, zero based
        /// </summary>
        public int Start { get; set; }

        /// <summary>
        /// Number of characters in range
        /// </summary>
        public int Length { get; set; }

        public string Word { get; set; }

        public PositionedWord(){}
        
        public PositionedWord(int start, int length, string word) {
            Start = start;
            Length = length;
            Word = word;
        }

        public bool AtSamePosition(object obj) {
            PositionedWord o = obj as PositionedWord;
            if(o==null)
                return false;
            return (this.Start==o.Start && this.Length==o.Length);
        }

        public static string GetWordFromPair(PositionedWord p, string text) {
            if (string.IsNullOrEmpty(text))
                return string.Empty;
            if (p.Start > text.Length || p.Start + p.Length > text.Length || p.Start < 0)
                return string.Empty;
            return text.Substring(p.Start, p.Length);
        }

        public static List<PositionedWord> FindAllPositionedWords(string text, int idx = 0) {

            List<PositionedWord> pairs = new List<PositionedWord>();

            while (idx < text.Length) {
                PositionedWord p = FindPositionedWord(idx, text);
                pairs.Add(p);
                idx = idx + p.Length + 1;
            }
            return pairs;
        }

        public static PositionedWord FindPositionedWord(int idx, string text) {

            PositionedWord word = new PositionedWord();
            if (idx < 0)
                idx = 0;

            word.Start = text.LastIndexOfAny(WORD_BREAK, idx) + 1;
            if (word.Start < 0)
                word.Start = 0;
            int stopIndex = text.IndexOfAny(WORD_BREAK, word.Start);
            if (stopIndex == -1)
                stopIndex = text.Length;
            word.Length = stopIndex - word.Start;
            if (word.Length < 0)
                word.Length = 0;

            word.Word = GetWordFromPair(word, text);

            return word;
        }

    }
}
 